using System;
using System.Collections;
using System.Collections.Generic;
using Main.AStar;
using Main.Audio;
using Main.CropPlant;
using Main.Details;
using Main.Event;
using Main.GameTime;
using Main.Inventory;
using Main.Item;
using Main.Map;
using Main.NPC;
using Main.Save;
using Main.Transition;
using UnityEngine;
using UnityEngine.SceneManagement;
using ZSW.Framework;
using ZSW.Main;

namespace Main
{
    public class MainLaunch : ZSWF_MonoBehaviour
    {
        [SerializeField] private SceneTransitionManager sceneManger;
        public List<GameObject> inits = new List<GameObject>();
        void Awake()
        {
            MainEventSystem.AfterLoadSceneEvent += InitSceneObject;

            DontDestroyOnLoad(this);

            ContainerRegister();

            // sceneManger.LoadFirstScene();
        }

        private void ContainerRegister()
        {
            // C#
            ZSWF_IOCContainer.Register(new ZSWF_GlobalSetting());
            // Mono
            ZSWF_IOCContainer.Register(InventoryManager.Instance);
            ZSWF_IOCContainer.Register(ItemManager.Instance);
            ZSWF_IOCContainer.Register(GridMapManager.Instance);
            ZSWF_IOCContainer.Register(CropManager.Instance);
            ZSWF_IOCContainer.Register(AStarController.Instance);
            ZSWF_IOCContainer.Register(NPCManager.Instance);
            ZSWF_IOCContainer.Register(TimeManager.Instance);
            ZSWF_IOCContainer.Register(SceneTransitionManager.Instance);
            ZSWF_IOCContainer.Register(SaveLoadManager.Instance);
            // SO
            ZSWF_IOCContainer.Register(ItemDataList_SO.Instance);
            ZSWF_IOCContainer.Register(InventoryBag_SO.Instance);
            ZSWF_IOCContainer.Register(BluePrintDataList_SO.Instance);
            ZSWF_IOCContainer.Register(SoundDetailsList_SO.Instance);

            Log($"IOC容器共添加 {ZSWF_IOCContainer.Count} 个组件 \n {ZSWF_IOCContainer.PrintAllInstances()}");

            InitSceneObject(false);
        }

        private void InitSceneObject()
        {
            InitSceneObject(true);
        }

        private void InitSceneObject(bool call)
        {
            int count = 0;
            foreach (var item in FindObjectsOfType<MonoBehaviour>(true))
            {
                foreach (var init in item.GetComponents<IInit>())
                {
                    if (!init.IsInit)
                    {
                        inits.Add(item.gameObject);
                        init.Init();
                        count++;
                        // Log($"物体:{item.gameObject.name} 初始化成功");
                    }
                }
            }

            Log($"场景:{SceneManager.GetActiveScene().name}初始化完成.总计 {count} 个对象.");

            if (call)
            {
                MainEventSystem.CallInitFinish();
            }
        }
    }
}